﻿using System;
using System.Net;
using System.Web.Mvc;
using RestUpMVC.Representation;

namespace RestUpMVC.Results
{
    /// <summary>
    /// A RESTful result.
    /// </summary>
    public class RestResult : ActionResult
    {
        /// <summary>
        /// Gets the HttpStatusCode for this result.
        /// </summary>
        public HttpStatusCode StatusCode { get; private set; }

        /// <summary>
        /// Gets the representation of the resource being returned.
        /// </summary>
        public IRepresentation Representation { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="RestResult"/> class.
        /// </summary>
        /// <param name="statusCode">The status code.</param>
        /// <param name="representation">The representation.</param>
        /// <exception cref="ArgumentNullException">Thrown if representation is null.</exception>
        public RestResult(HttpStatusCode statusCode, IRepresentation representation)
        {
            if (representation == null) throw new ArgumentNullException("representation");

            StatusCode = statusCode;
            Representation = representation;
        }

        #region Overrides of ActionResult

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.HttpContext.Response.StatusCode = (int)StatusCode;
            context.HttpContext.Response.Write(Representation.ConvertResource());
            context.HttpContext.Response.ContentType = Representation.ContentType;
        }

        #endregion
    }
}